<template>
  <div id="command-map-container" ref="mapContainer"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';

// 高德地图配置
const API_KEY = 'e67f0e9520643f148baa0e9747a27038';
const MAP_CONFIG = {
  resizeEnable: true,
  zoom: 12,
  center: [84.905, 45.583], // 克拉玛依中心位置
  viewMode: '2D',
  mapStyle: 'amap://styles/normal'
};

// 定义类型
type MapPoint = {
  id: string | number;
  name: string;
  lng: number;
  lat: number;
  statusDescription: string;
};

type MapIncident = {
  id: string | number;
  title: string;
  lng: number;
  lat: number;
  type: string;
  address: string;
};

// 组件属性
const props = defineProps({
  officers: {
    type: Array as () => MapPoint[],
    default: () => []
  },
  incidents: {
    type: Array as () => MapIncident[],
    default: () => []
  }
});

// 组件状态
const mapContainer = ref<HTMLElement | null>(null);
const map = ref<any>(null);
const infoWindow = ref<any>(null);
const officerMarkers = ref<any[]>([]);
const incidentMarkers = ref<any[]>([]);

// 关键修复：确保只加载一次API
let mapLoaded = false;

// 初始化地图
const initMap = async () => {
  if (!mapContainer.value || mapLoaded) return;

  try {
    // 动态加载高德地图脚本
    await new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = `https://webapi.amap.com/maps?v=2.0&key=${API_KEY}&plugin=AMap.InfoWindow,AMap.ToolBar,AMap.Scale,AMap.MapType`;
      script.onload = resolve;
      script.onerror = reject;
      document.head.appendChild(script);
    });

    // 标记已加载，防止重复加载
    mapLoaded = true;

    createMapInstance();

    // 添加控件
    map.value.addControl(new window.AMap.ToolBar());
    map.value.addControl(new window.AMap.Scale());
    map.value.addControl(new window.AMap.MapType());

    // 创建信息窗体
    infoWindow.value = new window.AMap.InfoWindow({
      offset: new window.AMap.Pixel(0, -25),
      closeWhenClickMap: true
    });

    // 应用数据
    renderOfficers();
    renderIncidents();

    // 自动适应地图尺寸
    nextTick(() => {
      map.value?.setFitView();
    });

  } catch (error) {
    console.error('地图初始化失败:', error);
  }
};

// 创建地图实例
const createMapInstance = () => {
  if (!mapContainer.value || !window.AMap) return;

  // 创建地图实例
  map.value = new window.AMap.Map(mapContainer.value, MAP_CONFIG);
};

// 渲染警员位置
const renderOfficers = () => {
  if (!map.value) return;

  // 清除旧标记
  officerMarkers.value.forEach(marker => map.value?.remove(marker));
  officerMarkers.value = [];

  // 创建新标记
  props.officers.forEach(officer => {
    if (!window.AMap) return;

    const marker = new window.AMap.Marker({
      position: [officer.lng, officer.lat],
      content: `
        <div class="officer-marker">
          <div class="status-indicator ${getStatusClass(officer.statusDescription)}"></div>
          <div class="name">${officer.name}</div>
        </div>
      `,
      offset: new window.AMap.Pixel(-15, -15),
      extData: officer
    });

    // 添加点击事件
    marker.on('click', (e: any) => {
      if (!infoWindow.value) return;

      const officerData = marker.getExtData();
      const infoContent = `
        <div class="police-info-window">
          <h4>${officerData.name}</h4>
          <div class="status-tag ${getStatusClass(officerData.statusDescription)}">
            ${officerData.statusDescription}
          </div>
          <div class="position-info">
            <p>经度: ${officerData.lng.toFixed(6)}</p>
            <p>纬度: ${officerData.lat.toFixed(6)}</p>
          </div>
          <button class="btn-view-profile">查看详情</button>
        </div>
      `;

      infoWindow.value.setContent(infoContent);
      infoWindow.value.open(map.value, marker.getPosition());
    });

    map.value.add(marker);
    officerMarkers.value.push(marker);
  });
};

// 渲染事件位置
const renderIncidents = () => {
  if (!map.value) return;

  // 清除旧标记
  incidentMarkers.value.forEach(marker => map.value?.remove(marker));
  incidentMarkers.value = [];

  // 创建新标记
  props.incidents.forEach(incident => {
    if (!window.AMap) return;

    // 获取事件类型图标
    const icon = getIncidentIcon(incident.type);

    const marker = new window.AMap.Marker({
      position: [incident.lng, incident.lat],
      content: `
        <div class="incident-marker">
          <div class="icon" style="background-color: ${icon.color}">${icon.text}</div>
        </div>
      `,
      offset: new window.AMap.Pixel(-12, -12),
      extData: incident
    });

    // 添加点击事件
    marker.on('click', (e: any) => {
      if (!infoWindow.value) return;

      const incidentData = marker.getExtData();
      const infoContent = `
        <div class="incident-info-window">
          <h4 class="incident-title">${incidentData.title}</h4>
          <div class="incident-location">
            <i class="icon-location"></i>
            <span>${incidentData.address || '位置信息未获取'}</span>
          </div>
          <div class="coordinates">
            <span class="coordinate">经度: ${incidentData.lng.toFixed(6)}</span>
            <span class="coordinate">纬度: ${incidentData.lat.toFixed(6)}</span>
          </div>
          <div class="actions">
            <button class="btn-action btn-dispatch">派警处理</button>
            <button class="btn-action btn-view-details">查看详情</button>
          </div>
        </div>
      `;

      infoWindow.value.setContent(infoContent);
      infoWindow.value.open(map.value, marker.getPosition());
    });

    map.value.add(marker);
    incidentMarkers.value.push(marker);
  });
};

// 获取警员状态类名
const getStatusClass = (status: string) => {
  const statusMap: Record<string, string> = {
    '执勤中': 'status-active',
    '巡逻中': 'status-on-duty',
    '响应中': 'status-responding',
    '待命中': 'status-on-standby',
    '已下班': 'status-off-duty'
  };

  return statusMap[status] || 'status-unknown';
};

// 获取事件类型图标
const getIncidentIcon = (type: string) => {
  const typeMap: Record<string, { text: string; color: string }> = {
    '交通事故': { text: '交', color: '#e74c3c' },
    '社区纠纷': { text: '社', color: '#3498db' },
    '治安事件': { text: '治', color: '#f39c12' },
    '火灾警报': { text: '火', color: '#d35400' },
    '医疗求助': { text: '医', color: '#9b59b6' },
    '设备故障': { text: '设', color: '#16a085' }
  };

  return typeMap[type] || { text: '事', color: '#7f8c8d' };
};

// 地图操作函数
const zoomIn = () => {
  if (map.value) {
    map.value.zoomIn();
  }
};

const zoomOut = () => {
  if (map.value) {
    map.value.zoomOut();
  }
};

const setFitView = () => {
  if (map.value) {
    const allMarkers = [...officerMarkers.value, ...incidentMarkers.value];
    if (allMarkers.length > 0) {
      map.value.setFitView(allMarkers);
    } else {
      // 默认视图
      map.value.setCenter(MAP_CONFIG.center);
      map.value.setZoom(MAP_CONFIG.zoom);
    }
  }
};

// 组件销毁时清理资源
const destroy = () => {
  if (map.value) {
    map.value.destroy();
    map.value = null;
    mapLoaded = false;
  }
};

// 暴露方法给父组件
defineExpose({
  zoomIn,
  zoomOut,
  setFitView,
  destroy
});

// 监听数据变化
watch(() => props.officers, renderOfficers, { deep: true });
watch(() => props.incidents, renderIncidents, { deep: true });

// 生命周期钩子
onMounted(() => {
  initMap();
});
onBeforeUnmount(destroy);
</script>

<style scoped>
#command-map-container {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  min-height: 500px;
}

/* 自定义标记样式 */
:deep(.officer-marker) {
  position: relative;
  width: 30px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.officer-marker .status-indicator) {
  width: 15px;
  height: 15px;
  border-radius: 50%;
  background-color: #3498db;
  border: 2px solid white;
  box-shadow: 0 1px 3px rgba(0,0,0,0.3);
}

:deep(.officer-marker .status-indicator.status-on-duty) {
  background-color: #2ecc71; /* 巡逻中 */
}

:deep(.officer-marker .status-indicator.status-responding) {
  background-color: #e74c3c; /* 响应中 */
}

:deep(.officer-marker .status-indicator.status-on-standby) {
  background-color: #f39c12; /* 待命中 */
}

:deep(.officer-marker .status-indicator.status-off-duty) {
  background-color: #7f8c8d; /* 已下班 */
}

:deep(.officer-marker .name) {
  display: none;
}

:deep(.incident-marker .icon) {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 13px;
  font-weight: bold;
  box-shadow: 0 1px 3px rgba(0,0,0,0.3);
  border: 1px solid white;
}

/* 信息窗样式 */
:deep(.amap-info-content) {
  padding: 12px !important;
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
  font-family: 'Microsoft YaHei', sans-serif !important;
  border: none !important;
  max-width: 260px !important;
  z-index: 2000 !important;
}

:deep(.amap-info-close) {
  top: 5px !important;
  right: 5px !important;
  color: #999 !important;
}

:deep(.police-info-window) {
  padding: 10px;
}

:deep(.incident-info-window) {
  padding: 10px;
}

:deep(.incident-info-window h4) {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.incident-info-window .incident-location) {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
  color: #7f8c8d;
  font-size: 13px;
  line-height: 1.4;
}

:deep(.incident-info-window .incident-location i) {
  margin-right: 5px;
  font-size: 12px;
  min-width: 16px;
  margin-top: 3px;
}

:deep(.incident-info-window .coordinates) {
  display: flex;
  gap: 15px;
  margin-bottom: 12px;
  font-size: 12px;
  color: #34495e;
  flex-wrap: wrap;
}

:deep(.incident-info-window .coordinate) {
  display: flex;
  align-items: center;
  background-color: #f8f9fa;
  padding: 3px 8px;
  border-radius: 4px;
}

:deep(.incident-info-window .actions) {
  display: flex;
  gap: 8px;
  margin-top: 10px;
  flex-wrap: wrap;
}

:deep(.btn-action) {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
  min-width: 80px;
  text-align: center;
}

:deep(.btn-dispatch) {
  background-color: #e74c3c;
  color: white;
}

:deep(.btn-view-details) {
  background-color: #3498db;
  color: white;
}

:deep(.btn-action:hover) {
  opacity: 0.9;
  transform: translateY(-1px);
}

@media (max-width: 768px) {
  #command-map-container {
    min-height: 400px;
  }

  :deep(.amap-info-content) {
    max-width: 220px !important;
  }

  :deep(.incident-info-window .actions) {
    flex-direction: column;
    gap: 6px;
  }

  :deep(.btn-action) {
    width: 100%;
  }
}
</style>
